package com.gogowan.agroenterprise.newview;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.gogowan.agroenterprise.MyApplication;
import com.gogowan.agroenterprise.R;
import com.gogowan.agroenterprise.SalesActivity;
import com.gogowan.agroenterprise.contorl.MyAsyncTask;
import com.gogowan.agroenterprise.model.IntMaterial;
import com.gogowan.agroenterprise.model.IntStorageInfoRequest;
import com.gogowan.agroenterprise.model.IntStorageInfoResult;
import com.gogowan.agroenterprise.model.LoginResultInfo;
import com.gogowan.agroenterprise.model.StoreListResult;
import com.gogowan.agroenterprise.model.StoreModel;
import com.gogowan.agroenterprise.model.StoreRequest;
import com.gogowan.agroenterprise.model.UserType;
import com.gogowan.agroenterprise.utils.Utils;
import com.gogowan.agroenterprise.widget.adapter.IntMaterialListViewAdapter;
import com.gogowan.agroenterprise.widget.adapter.StoreSpinnerAdapter;

/**
 * 仓储界面
 * 
 * @author tjh 2017-01-16
 *
 */
public class NewInventoryActivity extends Activity implements OnClickListener, AdapterView.OnItemSelectedListener {
	private ProgressDialog progressDialog;
	
	private List<StoreModel> storeList = new ArrayList<StoreModel>();
	private List<String> storeListName = new ArrayList<String>();
	private long storeID = -1;
	private Spinner ckSpinner;
	// private StoreSpinnerAdapter storeSpinnerAdapter;
	private ArrayAdapter<String> adapter;
	private List<IntMaterial> intMaterialList = new ArrayList<IntMaterial>();
	private IntMaterialListViewAdapter intMaterialListViewAdapter;
	private ListView intMaterialListView;
	private Handler myHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch (msg.what) {
			case 0:
				if (storeList.size()<1){
					Toast.makeText(NewInventoryActivity.this, "当前没有仓库", Toast.LENGTH_LONG).show();
					return;
				}
				adapter.notifyDataSetChanged();
				storeID = storeList.get(0).getStoreID();
				progressDialog.show();
				IntStorageInfoRequest intStorageInfoRequest = new IntStorageInfoRequest();
				intStorageInfoRequest.setStoreId((int) storeID);
				//intStorageInfoRequest.setEnterpriseId((MyApplication.mSettings.getInt("usertype",0)== UserType._JING_XIAO_SHANG.getTypeID()?loginResultInfo.getEnterpriseinfo().getDealerId():loginResultInfo.getEnterpriseinfo().getEnterpriseid()));

				GetIntMaterialListAsyn getIntMaterialListAsyn = new GetIntMaterialListAsyn();
				getIntMaterialListAsyn.execute(intStorageInfoRequest);
				break;
			case 1:
				intMaterialListViewAdapter.notifyDataSetChanged();
				break;
			default:
				break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.new_activity_inventory);

		initView();
		initValue();
	}

	/**
	 * 初始化界面
	 */
	private void initView() {
		// 选择仓库
		ckSpinner = (Spinner) findViewById(R.id.inventory_xzck_spinner);
		// storeSpinnerAdapter = new StoreSpinnerAdapter(this, storeList,
		// ckSpinner);
		// ckSpinner.setAdapter(storeSpinnerAdapter);
		// 重写adapter
		adapter = new ArrayAdapter<String>(NewInventoryActivity.this, R.layout.simple_spinner_item1, storeListName) {

			@Override
			public View getDropDownView(int position, View convertView, ViewGroup parent) {
				View view = View.inflate(getContext(), R.layout.new_activity_store_spinner_item, null);
				TextView label = (TextView) view.findViewById(R.id.store_spinner_item_ckmc_text);
				ImageView check = (ImageView) view.findViewById(R.id.store_spinner_item_ckmc_cb);
				label.setText(storeListName.get(position));
				if (ckSpinner.getSelectedItemPosition() == position) {
					check.setImageResource(R.drawable.invent_select);
					// viewHolder.selectBtn.setVisibility(View.GONE);
				} else {
					check.setImageResource(R.drawable.invent_noselect);
				}
				return view;
			}
		};

		adapter.setDropDownViewResource(R.layout.new_activity_store_spinner_item);

		// 将adapter 添加到spinner中
		ckSpinner.setAdapter(adapter);
		ckSpinner.setOnItemSelectedListener(this);
		intMaterialListView = (ListView) findViewById(R.id.inventory_xmlist);
		intMaterialListViewAdapter = new IntMaterialListViewAdapter(this, intMaterialList);
		intMaterialListView.setAdapter(intMaterialListViewAdapter);

		ImageButton fhBtn = (ImageButton) findViewById(R.id.inventory_fh_btn);
		fhBtn.setOnClickListener(this);
	}

	/**
	 * 初始化数据
	 */
	private void initValue() {
		SharedPreferences preferences = getSharedPreferences("LoginINfo", MODE_PRIVATE);
		
		

		progressDialog = ProgressDialog.show(this, getString(R.string.alert_title), getString(R.string.alert_message),
				true, false);

		StoreRequest storeRequest = new StoreRequest();
		//storeRequest.setEnterpriseID(loginResultInfo.getEnterpriseinfo().getEnterpriseid());
		//storeRequest.setDealerID(loginResultInfo.getEnterpriseinfo().getDealerId());
		storeRequest.setUserType(MyApplication.mSettings.getInt("usertype",0));
		storeRequest.setUserID(MyApplication.mSettings.getLong("personid",0));
		storeRequest.setPageIndex(1);
		storeRequest.setType(0);
		storeRequest.setParentCode(0);

		GetStorageListAsyn getStorageListAsyn = new GetStorageListAsyn();
		getStorageListAsyn.execute(storeRequest);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.inventory_fh_btn:
			// 返回
			this.finish();
			break;
		default:
			break;
		}
	}

	@Override
	public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
		// ckSpinner.setSelection(position);
		// TODO Auto-generated method stub
		storeID = storeList.get(position).getStoreID();
		progressDialog = ProgressDialog.show(this, getString(R.string.alert_title), getString(R.string.alert_message),
				true, false);

		IntStorageInfoRequest intStorageInfoRequest = new IntStorageInfoRequest();
		intStorageInfoRequest.setStoreId((int) storeID);
		//intStorageInfoRequest.setEnterpriseId((MyApplication.mSettings.getInt("usertype",0)== UserType._JING_XIAO_SHANG.getTypeID()?loginResultInfo.getEnterpriseinfo().getDealerId():loginResultInfo.getEnterpriseinfo().getEnterpriseid()));

		GetIntMaterialListAsyn getIntMaterialListAsyn = new GetIntMaterialListAsyn();
		getIntMaterialListAsyn.execute(intStorageInfoRequest);
	}

	@Override
	public void onNothingSelected(AdapterView<?> parent) {
		// TODO Auto-generated method stub

	}

	/**
	 * 获取仓库列表
	 * 
	 * @author tjh
	 *
	 */
	private class GetStorageListAsyn extends MyAsyncTask {

		@Override
		protected void onPostExecute(Object res) {
			progressDialog.dismiss();
			if (res == null || res.equals("")) {
				Toast.makeText(NewInventoryActivity.this, getString(R.string.server_error), Toast.LENGTH_LONG).show();
			} else {
				com.gogowan.agroenterprise.model.Message message = (com.gogowan.agroenterprise.model.Message) Utils
						.fromJSON((String) res, com.gogowan.agroenterprise.model.Message.class);
				String string = Utils.getMessageContent(message);

				if (string == null || string.equals("")) {
					Toast.makeText(NewInventoryActivity.this, getString(R.string.analyse_error), Toast.LENGTH_LONG)
							.show();
				} else {
					StoreListResult storeListResult = (StoreListResult) Utils.fromJSON(string, StoreListResult.class);
					if (storeListResult.getResult() == 21000) {
						if (storeListResult.getStoreList() != null) {
							storeList.clear();
							storeListName.clear();
							for (int i = 0; i < storeListResult.getStoreList().size(); i++) {
								if (storeListResult.getStoreList().get(i).getType() == 1) {
									storeList.add(storeListResult.getStoreList().get(i));
									storeListName.add(storeListResult.getStoreList().get(i).getStoreName());
								}
							}
						}

						myHandler.sendEmptyMessage(0);
					} else {
						Toast.makeText(NewInventoryActivity.this, storeListResult.getResultinfo(), Toast.LENGTH_LONG)
								.show();
					}
				}
			}
			super.onPostExecute(res);
		}

		@Override
		protected Object doInBackground(Object... params) {
			StoreRequest storeRequest = (StoreRequest) params[0];
			String json = Utils.toJSON(storeRequest);
			com.gogowan.agroenterprise.model.Message message = new com.gogowan.agroenterprise.model.Message(21000, true,
					json);
			// String ss = Utils.toJSON(message);
			// Log.i("gggggggggggggggggg===", ss);
			String res = Utils.postCommit(getString(R.string.first_url) + getString(R.string.first_url_page), message);
			return res;
		}
	}

	/**
	 * 获取仓储列表
	 * 
	 * @author tjh
	 *
	 */
	private class GetIntMaterialListAsyn extends MyAsyncTask {

		@Override
		protected void onPostExecute(Object res) {
			if (res == null || res.equals("")) {
				Toast.makeText(NewInventoryActivity.this, getString(R.string.server_error), Toast.LENGTH_LONG).show();
			} else {
				com.gogowan.agroenterprise.model.Message message = (com.gogowan.agroenterprise.model.Message) Utils
						.fromJSON((String) res, com.gogowan.agroenterprise.model.Message.class);
				String string = Utils.getMessageContent(message);

				if (string == null || string.equals("")) {
					Toast.makeText(NewInventoryActivity.this, getString(R.string.analyse_error), Toast.LENGTH_LONG)
							.show();
				} else {
					IntStorageInfoResult intStorageInfoResult = (IntStorageInfoResult) Utils.fromJSON(string,
							IntStorageInfoResult.class);
					if (intStorageInfoResult.getResult() > 0) {
						if (intStorageInfoResult.getStoreList() != null) {
							intMaterialList.clear();
							intMaterialList.addAll(intStorageInfoResult.getStoreList());
							myHandler.sendEmptyMessage(1);
						}
					} else {
						if (intStorageInfoResult.getStoreList() != null
								&& intStorageInfoResult.getStoreList().size() == 0) {
							intMaterialList.clear();
							myHandler.sendEmptyMessage(1);
						}
						Toast.makeText(NewInventoryActivity.this, intStorageInfoResult.getResultinfo(),
								Toast.LENGTH_LONG).show();
					}
				}
			}
			progressDialog.dismiss();
			super.onPostExecute(res);
		}

		@Override
		protected Object doInBackground(Object... params) {
			IntStorageInfoRequest intStorageInfoRequest = (IntStorageInfoRequest) params[0];
			String json = Utils.toJSON(intStorageInfoRequest);
			com.gogowan.agroenterprise.model.Message message = new com.gogowan.agroenterprise.model.Message((MyApplication.mSettings.getInt("usertype",0)== UserType._JING_XIAO_SHANG.getTypeID()?185001:185000),
					true, json);
			// String ss = Utils.toJSON(message);
			// Log.i("gggggggggggggggggg===", ss);
			String res = Utils.postCommit(getString(R.string.first_url) + getString(R.string.first_url_page), message);
			return res;
		}
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}

}
